package cn.yunhe.crm.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;

import cn.yunhe.crm.annotation.SystemLog;
import cn.yunhe.crm.entity.Contract;
import cn.yunhe.crm.entity.Orders;
import cn.yunhe.crm.entity.Organization;
import cn.yunhe.crm.service.ContractService;
import cn.yunhe.crm.service.OrderBiz;
import cn.yunhe.crm.service.OrganizationService;
@Controller
public class OrderController {
	/**
	 * 订单service层
	 */
	@Autowired
	@Qualifier("orderbiz")
	private OrderBiz ob;

	public void setOb(OrderBiz ob) {
		this.ob = ob;
	}
	/**
	 * 机构service层，主要用于获取订单列表功能
	 */
	@Autowired
	@Qualifier("OrganizationService")
	private OrganizationService orgBiz;
	
	public void setOrgBiz(OrganizationService orgBiz) {
		this.orgBiz = orgBiz;
	}
	/**
	 * 合同service层，用于添加订单时对合同名判断
	 * 以及更新订单信息时获取所需信息以及更新合同时做验证
	 */
	
	@Autowired
	@Qualifier("ContractService")
	private ContractService contractbiz;
	public void setContractbiz(ContractService contractbiz) {
		this.contractbiz = contractbiz;
	}

	/**
	 * 通用信息，获取条件下的orders
	 * @param o
	 * @param currentPage
	 * @return
	 */
	public List<Map> getOrder(Map m){
		List<Map> mlist = null;
		//获取当前页面的所有orders
		List<Orders> list = ob.getOrderList(m);
		
		if(list!=null){
			mlist = new ArrayList<Map>();
		for (Orders orders : list) {
			Map map = new HashMap();
			map.put("id", orders.getId());
			map.put("oname", orders.getName());
			Organization o = orgBiz.getOrgById(orders.getOid());
			//机构名称
			map.put("orgname",o.getName());
			//经办人,经办人信息存储于联系人中，取机构信息时通过外键把联系人信息取出，获取到了经办人名称
			map.put("ename", o.getContact().getEname());
			//联系人姓名
			map.put("contact", o.getContact().getName());
			//产品状态
			map.put("prostate", orders.getProductstate());
			//使用状态
			map.put("usestate", orders.getUsestate());
			//开通日期
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String date = df.format(orders.getPassdate());
			map.put("passdate", date);
			
			mlist.add(map);
			}
		}	
		return mlist;
		
	}
	
	/**
	 * 获取所有的订单信息
	 * @return
	 */
	@RequestMapping("/getAllOrders.do")
	public String getAllOrders(HttpSession session){
		List<Map> list = getOrder(null);
		session.setAttribute("orderlist", list);
		return "productmanage";
		
	}
	
	/**
	 * 根据id获取订单,合同，机构，联系人等信息
	 * 更新订单信息
	 * @param req
	 * @return
	 */
	@RequestMapping("/toupdateOrder.do")
	public String toupdateOrder(@RequestParam Integer id,HttpServletRequest req){
		Orders order = ob.selectOrderById(id);
		Map map = new HashMap();
		if(order!=null){
			map = getOrderDetail(map,order);
			req.setAttribute("map", map);
		}else{
			map.put("error", "此订单信息不存在");
		}
		return "productmanageupdate";
	}
	/**
	 * 跳转到查看页面
	 * @return
	 */
	@RequestMapping("/toproductDetail.do")
	public String toproductDetail(@RequestParam Integer id,HttpServletRequest req){
		Orders order = ob.selectOrderById(id);
		Map map = new HashMap();
		if(order!=null){
			map = getOrderDetail(map,order);
			req.setAttribute("map", map);
		}else{
			map.put("error", "此订单信息不存在");
		}
		return "productmanagedetail";
	}
	
	
	
	/**
	 * 跳转到新增订单页面
	 * @return
	 */
	@RequestMapping("/toaddOrder.do")
	public String toaddOrder(){
		return "productmanage_add";
	}
	
	/**
	 * 添加新订单
	 * @return
	 * @throws IOException 
	 */
	@SystemLog(des="新增订单")
	@RequestMapping("/addOrder.do")
	public String addOrder(Orders order,String spassdate,HttpServletResponse response) throws IOException{
		order.setDelstate(0);
		
		//对时间进行转换，从String转换为date类型
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sdf.parse(spassdate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		order.setPassdate(date);
		
		//新增订单信息
		boolean r = ob.addOrder(order);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		if(r){
			
			return "forward:getAllOrders.do";
		}else{
			return "forward:toaddOrder.htm";
		}
		
	}
	/**
	 * 修改订单信息
	 * @return
	 */
	@SystemLog(des="更新订单")
	@RequestMapping("/updateOrder.do")
	public String updateOrder(Orders order,String spassdate,HttpServletResponse response){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sdf.parse(spassdate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		order.setPassdate(date);
		
		boolean r = ob.updateOrder(order);
		if(r){
			return "forward:getAllOrders.do";
		}else{
			return "forward: toupdateOrder.do";
		}
	}
	
	/**
	 * 删除对应订单
	 * @param oid
	 * @return
	 */
	@SystemLog(des="删除订单")
	@RequestMapping("/orderDel.do")
	public String orderDel(Integer oid){
		
		boolean r = ob.delOrderById(oid);
		return "forward:getAllOrders.do";
	}
	
	/**
	 * 对订单名做唯一性验证
	 * 若订单名存在，返回false，反之返回true
	 * @return json
	 */
	@ResponseBody
	@RequestMapping("/checkOrder.do")
	public Object checkOrder(@RequestParam String oname){
		Map map = new HashMap();
		//手动对json传输数据进行转码
		String name = null;
		try {
			name = new String(oname.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		boolean r = ob.checkOrderByName(name);
		if(r){
			map.put("result", "true");
		}else{
			map.put("result", "false");
		}
		return JSONArray.toJSONString(map);
	}
	
	/**
	 * 跳转到更新或者查看页面前的通用方法，获取订单的所有信息
	 * @param map
	 * @param order
	 * @return
	 */
	public Map getOrderDetail(Map map,Orders order){
		map.put("id",order.getId());
		map.put("name",order.getName());
		//产品状态
		map.put("productstate", order.getProductstate());
		//使用状态
		map.put("usestate", order.getUsestate());
		//将日期从date转化成String
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String passdate = sdf.format(order.getPassdate());
		//存入map中
		map.put("spassdate", passdate);
		//筛选合同的id条件
		map.put("conditionid", order.getCoid());
		Contract c = contractbiz.getContractByMap(map);
		//根据通用方法把获取到的合同存入map
		map = getMapForContract(map,c);
		return map;
	}
	
	
	/**
	 * 通用方法
	 * 对获取到的合同信息进行修改，只取需要的信息存入map中
	 * @return
	 */
	public Map getMapForContract(Map map,Contract c){
		//合同名
		map.put("contractName", c.getName());
		//合同id
		map.put("coid", c.getId());
		//机构名称
		map.put("orgname", c.getOrganization().getName());
		//机构id
		map.put("oid", c.getOrganization().getId());
		//产品类别
		map.put("apro", c.getAproduct());
		map.put("bpro", c.getBproduct());
		map.put("cpro", c.getCproduct());
		//合同审核状态
		map.put("checkstate", c.getCheckstate());
		//经办人
		map.put("ename", c.getOrganization().getContact().getEname());
		//联系人
		map.put("cname", c.getOrganization().getContact().getName());
		
		return map;
	}
	
	/**
	 * 获取所有的合同名，用于自动补全
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getContractNameList")
	public Object getContractNameList(){
		List list = new ArrayList();
		List<Contract> contractList = contractbiz.contractlist(null);
		for (Contract con : contractList) {
			Map map = new HashMap();
			//直接把所有获取到的合同信息返回到前台
			map=getMapForContract(map,con);
			list.add(map);
		}
		return JSONArray.toJSONString(list);
	}
}
